package com.shawn.springboot.integeration.common.config.shiro.token;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.JWTVerifier;

import java.util.Date;

/**
 * @author shawn
 * @description: JWT 工具类
 * @date 2023/12/17
 */
public class JWTUtil {
    // 过期时间 24 小时
    private static final long EXPIRE_TIME = 60 * 24 * 60 * 1000;

   // 生成 token
    public static String createToken(String username,String secret) {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(secret);
        // 附带 username信息,指定到期时间,并指定算法进行加密
        return JWT.create().withClaim("username", username)
                .withExpiresAt(date).sign(algorithm);
    }
    // 校验 token 是否正确
    public static boolean verify(String token, String username,String secret) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("username", username).build();
            verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }
    // 获得token中的信息，无需secret解密也能获得
    public static String getUsername(String token) {
        try {
            return JWT.decode(token).getClaim("username").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }
}
